/**
 * 资源预加载器
 */
export class ResourcePreloader {
  constructor() {
    this.preloadMap = new Map();
  }

  preloadImage(url) {
    return new Promise((resolve, reject) => {
      if (this.preloadMap.has(url)) return resolve();

      const img = new Image();
      img.src = url;
      img.onload = () => {
        this.preloadMap.set(url, true);
        resolve();
      };
      img.onerror = reject;
    });
  }

  preloadImages(urls) {
    return Promise.all(urls.map(url => this.preloadImage(url)));
  }

  preloadFont(fontFamily, fontUrl) {
    return new Promise((resolve, reject) => {
      if (this.preloadMap.has(fontUrl)) return resolve();

      const fontFace = new FontFace(fontFamily, `url(${fontUrl})`);
      fontFace.load()
        .then(loadedFace => {
          document.fonts.add(loadedFace);
          this.preloadMap.set(fontUrl, true);
          resolve();
        })
        .catch(reject);
    });
  }

  preloadScript(url, type = 'text/javascript') {
    return new Promise((resolve, reject) => {
      if (this.preloadMap.has(url)) return resolve();

      const script = document.createElement('script');
      script.src = url;
      script.type = type;
      script.async = false;
      script.onload = () => {
        this.preloadMap.set(url, true);
        resolve();
      };
      script.onerror = reject;
      document.head.appendChild(script);
    });
  }

  prefetchResource(url, type = 'fetch') {
    return new Promise((resolve, reject) => {
      const link = document.createElement('link');
      link.rel = type === 'fetch' ? 'prefetch' : 'preload';
      link.href = url;
      link.as = type;
      link.onload = resolve;
      link.onerror = reject;
      document.head.appendChild(link);
    });
  }
}

/**
 * 关键资源预加载Hook
 */
export const useCriticalPreload = (resources) => {
  useEffect(() => {
    const preloader = new ResourcePreloader();

    const preloadCritical = async () => {
      const { images, fonts, scripts } = resources;
      
      try {
        if (images?.length) await preloader.preloadImages(images);
        if (fonts?.length) {
          await Promise.all(fonts.map(font => 
            preloader.preloadFont(font.family, font.url)
          ));
        }
        if (scripts?.length) {
          await Promise.all(scripts.map(script =>
            preloader.preloadScript(script.url, script.type)
          ));
        }
      } catch (error) {
        console.error('Preload failed:', error);
      }
    };

    if (typeof window
